/*
 * @Author: xiongchao
 * @Date: 2023-08-14 15:21:01
 * @LastEditors: xiongchao
 * @LastEditTime: 2023-12-07 15:53:18
 * @Description: TODO
 */
import { createStore, Store } from 'vuex';
import VuexPersistense from "vuex-persistedstate";

// 定义状态的类型
interface State {
  count: number; // 计数器
  message: string; // 消息
  userInfo: any; // 用户信息
}

// 定义 Mutations 的类型
type Mutations<S = State> = {
  increment(state: S): void; // 计数器加一
  setMessage(state: S, msg: string): void; // 设置消息
  setUser(state: S, user: any): void; // 设置用户信息
};

// 定义 Actions 的类型
type Actions<S = State> = {
  incrementAsync({ commit }: { commit: (mutation: keyof Mutations<S>, ...args: any[]) => void }): void; // 异步计数器加一
  setMessageAsync({ commit }: { commit: (mutation: keyof Mutations<S>, ...args: any[]) => void }, msg: string): void; // 异步设置消息
};

// 定义 Getters 的类型
type Getters<S = State> = {
  getCount(state: S): number; // 获取计数器的值
  getMessage(state: S): string; // 获取消息的值
  getUser(state: S): any; // 获取用户信息
};

const store: Store<State> = createStore({
  state() {
    return {
      count: 0, // 计数器
      message: '', // 消息
      userInfo: {}
    };
  },
  mutations: {
    increment(state) { // 计数器加一
      state.count++;
    },
    setMessage(state, msg) { // 设置消息
      state.message = msg;
    },
    setUser(state, user) {
      state.userInfo = user;
    }
  },
  actions: {
    incrementAsync({ commit }) { // 异步计数器加一
      setTimeout(() => {
        commit('increment');
      }, 1000);
    },
    setMessageAsync({ commit }, msg) { // 异步设置消息
      setTimeout(() => {
        commit('setMessage', msg);
      }, 1000);
    }
  },
  getters: {
    getCount: state => state.count, // 获取计数器的值
    getMessage: state => state.message, // 获取消息的值
    getUser: state => state.userInfo
  },
  plugins: [new VuexPersistense({
    storage: sessionStorage
  })]
});

export default store;